package abcy.cloud.authenticationserver.services.impls;

import abcy.cloud.authenticationserver.dto.req.SysClientAddReq;
import abcy.cloud.authenticationserver.dto.req.SysClientSelectReq;
import abcy.cloud.authenticationserver.dto.resp.SysClientSelectResp;
import abcy.cloud.authenticationserver.entities.OauthClientDetails;
import abcy.cloud.authenticationserver.mappers.OauthClientDetailsMapper;
import abcy.cloud.authenticationserver.services.OauthClientDetailsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OauthClientDetailsServiceImpl implements OauthClientDetailsService {
    @Autowired
    private OauthClientDetailsMapper sysClientMapper;

    @Override
    public void addSysClient(SysClientAddReq sysClientAddReq) {
        OauthClientDetails oauthClientDetails = new OauthClientDetails();
        BCryptPasswordEncoder bCryPasswordEncoder = new BCryptPasswordEncoder();
        List<String> scopesList = sysClientAddReq.getScopesList();
        String scope = String.join(",",scopesList);
        sysClientAddReq.setScope(scope);
        List<String> grantTypesList = sysClientAddReq.getGrantTypesList();
        String grantTypes = String.join(",", grantTypesList);
        sysClientAddReq.setClientSecret(bCryPasswordEncoder.encode(sysClientAddReq.getClientSecret()));
        BeanUtils.copyProperties(sysClientAddReq,oauthClientDetails);
        oauthClientDetails.setAuthorizedGrantTypes(grantTypes);
        sysClientMapper.insert(oauthClientDetails);
    }

    @Override
    public PageInfo<SysClientSelectResp> getClientForPage(SysClientSelectReq sysClientSelectReq) {
        PageHelper.startPage(sysClientSelectReq.getPageIndex(), sysClientSelectReq.getPageSize());
        String scopes = String.join(",",sysClientSelectReq.getScopesList());
        String grantType = String.join(",", sysClientSelectReq.getGrantTypesList());
        sysClientSelectReq.setScopes(scopes);
        sysClientSelectReq.setGrantTypes(grantType);
        List<SysClientSelectResp> clientList = sysClientMapper.getClientForPage(sysClientSelectReq);
        PageInfo<SysClientSelectResp> pageInfo = new PageInfo<>(clientList);
        return pageInfo;
    }

    @Override
    public void deleteByClientId(String clientId) {
        sysClientMapper.deleteByClientId(clientId);
    }
}
